﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Claims;
using System.Text;
using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Primitives;
using AspNetCore.Web.Model;
using AspNetCore.Web.Security.Provider;

namespace AspNetCore.Web.Security
{
    /// <summary>
    /// 
    /// </summary>
    public class AdminAuthorization : IAdminAuthorization
    {
        private IHttpContextAccessor _httpContextAccessor;
        private ITokenProvider _tokenProvider;

        /// <summary>
        /// 
        /// </summary>
        /// <param name="httpContextAccessor"></param>
        /// <param name="tokenProvider"></param>
        public AdminAuthorization(IHttpContextAccessor httpContextAccessor,
            ITokenProvider tokenProvider)
        {
            _tokenProvider = tokenProvider;
            _httpContextAccessor = httpContextAccessor;
        }

        /// <summary>
        /// 登陆后可获取token
        /// </summary>
        public string Token
        {
            get
            {
                return _tokenProvider.GetToken(CookieAdminAuthInfo.AuthenticationScheme, CookieAdminAuthInfo.ClaimsIssuer, "AdminToken");
            }
        }

        /// <summary>
        /// 获取当前登录用户
        /// （缓存）
        /// </summary>
        /// <param name="func">委托，执行后返回：Administrator</param>
        /// <returns></returns>
        public Administrator GetCurrentUser(Func<string, Administrator> func)
        { 
            return func(Token);
        }
         
        /// <summary>
        /// 获取我的权限数据
        /// </summary>
        /// <param name="func">委托，执行后返回：CategoryInfo 集合 </param>
        /// <returns></returns>
        public List<CategoryInfo> GetMyCategories(Func<List<CategoryInfo>> func)
        {
            return func();
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="name">姓名</param>
        /// <param name="func">委托，在保存cookie前执行</param>
        public void SignIn(string name, Func<string> func)
        {
            string token = func();
            //保存登陆信息
            _tokenProvider.Store(CookieAdminAuthInfo.AuthenticationScheme, token, name, CookieAdminAuthInfo.ClaimsIssuer); 
        }

        /// <summary>
        /// 退出登录
        /// </summary>
        public void SignOut()
        {
            _httpContextAccessor.HttpContext.SignOutAsync(CookieAdminAuthInfo.AuthenticationScheme);
        }
         
    }
}
